package com.qjc.filter;

import cn.hutool.core.net.NetUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import static org.apache.logging.log4j.util.Strings.isNotBlank;

/**
 * @Description: 自定义过滤器1
 * @Author: qjc
 * @Date: 2020/4/20
 */
@Slf4j
/**
 * 如果用此注解，一定要在配置类中加另外一个注解：@ServletComponetScan，指定扫描的包。
 * 过滤器执行顺序会按照filterName的字母顺序进行
 * @WebFilter指定的过滤器优先级都高于FilterRegistrationBean配置的过滤器
 */
@WebFilter(urlPatterns = "/*", filterName = "aaaa")
public class TestFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        log.info("过滤器1初始化！！！！");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;


        HttpServletRequest httpReq = (HttpServletRequest) req;
        String ctxPath = httpReq.getContextPath();
        String requestUri = httpReq.getRequestURI(); // 请求的全路径,比如:
        String uri = requestUri.substring(ctxPath.length());// 全路径除去ctxPath
        String tarUri = uri.trim();
        if (tarUri.equals("/") || tarUri.equals("/a")) {
            fc.doFilter(req, res);
            return;
        }
        String localhostStr = NetUtil.getLocalhostStr();
        log.info("=============服务器地址=================="+localhostStr);
        log.info("=============拦截==================");
        log.info("=============请求ip:" + getRemoteAddr(httpReq) + "=============");
        log.info("=============请求路径" + tarUri + "=============");
        Map<String, String[]> a = httpReq.getParameterMap();
        log.info("=============请求参数:" + getParamString(a) + "=============");
        Cookie[] cookies = httpReq.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                log.info("=============cookies：" + cookies[i].getName() + "-" + cookies[i].getValue() + "=============");
            }
        } else {
            log.info("=============无cookies=============");
        }
        if (httpReq.getHeaderNames().hasMoreElements()) {
            log.info("=============请求头：" + httpReq.getHeaderNames().nextElement() + ":" + httpReq.getParameter(httpReq.getHeaderNames().nextElement()) + "=============");
        }

        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setHeader("Accept", "application/json");

        response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题
        response.setHeader("Access-Control-Allow-Credentials", "true");

        CustomHttpServletResponse cresponse = new CustomHttpServletResponse((HttpServletResponse) response);
        //		chain.doFilter(request,cresponse);
        //      cresponse.flushBuffer();
        //		fc.doFilter(req, res);
        fc.doFilter(req, cresponse);
        byte[] data = cresponse.getCopy();
        String htmStr = new String(data, response.getCharacterEncoding());
        log.info("=============请求响应:" + htmStr + "=============");
        log.info("=============session拦截结束==================");

//        log.info("过滤器1开始！！！！");
//        long start = System.currentTimeMillis();
//        filterChain.doFilter(servletRequest, servletResponse);
//        log.info("过滤器1结束！！！！耗时：" + (System.currentTimeMillis() - start) + "ms");
    }

    @Override
    public void destroy() {
        //当Filter被移除或服务器正常关闭时
        log.info("过滤器1销毁！！！！");
    }

    private String getParamString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String[]> e : map.entrySet()) {
            sb.append(e.getKey()).append("=");
            String[] value = e.getValue();
            if (value != null && value.length == 1) {
                sb.append(value[0]).append("\t");
            } else {
                sb.append(Arrays.toString(value)).append("\t");
            }
        }
        return sb.toString();
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }


}
